﻿/*----------------------------------------------------------------
  //Copyright (C) 2011 赵国伟
  //文件名：EvalHelper.cs
  //文件功能描述：动态求值程序。原理，反射，调用JScript编译器，执行JScript.NET中的Eval方法。用法：EvalHelper.Eval();
  //创建人：赵国伟
  //创建时间：2011-09-08 10:45:23
//----------------------------------------------------------------*/
using System;
using System.CodeDom.Compiler;
using System.Reflection;

namespace Shopping.Common
{
    /// <summary>
    /// 动态求值 用法：EvalHelper.Eval();
    /// </summary>
    public class EvalHelper
    {
        /// <summary>
        /// 计算结果,如果表达式出错则抛出异常
        /// </summary>
        /// <param name="statement">表达式,如"1+2+3+4"</param>
        /// <returns>结果</returns>
        public static object Eval(string statement)
        {
            return _evaluatorType.InvokeMember(
                        "Eval",
                        BindingFlags.InvokeMethod,
                        null,
                        _evaluator,
                        new object[] { statement }
                     );
        }
        /// <summary>
        /// 静态构造函数，故只会执行一次动态编译。
        /// </summary>
        static EvalHelper()
        {
            //构造JScript的编译驱动代码
            CodeDomProvider provider = CodeDomProvider.CreateProvider("JScript");

            CompilerParameters parameters;
            parameters = new CompilerParameters();
            parameters.GenerateInMemory = true;

            CompilerResults results;
            results = provider.CompileAssemblyFromSource(parameters, _jscriptSource);

            Assembly assembly = results.CompiledAssembly;
            _evaluatorType = assembly.GetType("Evaluator");
            _evaluator = Activator.CreateInstance(_evaluatorType);
        }

        private static object _evaluator = null;
        private static Type _evaluatorType = null;
        /// <summary>
        /// JScript代码
        /// </summary>
        private static readonly string _jscriptSource =

            @"class Evaluator
              {
                  public function Eval(expr : String) : String 
                  { 
                     return eval(expr); 
                  }
              }";
    }
}
